<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
<form action="" onsubmit="return false">
    <h1>多人聊天</h1>
    <textarea id="msgTxt" cols="50" rows="20">

		       </textarea><br>
    <input type="text" name="msg" style="width: 300px">
    <input type="button" value="发送" onclick="send(this.form.msg.value)">
    <input type="button" value="清空">
</form>

<script type="text/javascript">

		  var socket   //定义对象
			  if(!window.WebSocket){

					   //有的浏览器里可能没有Websocket对象，window就代表浏览器，就做一下兼容性处理
					   window.WebSocket=window.MozWebSocket;
				   }
		       if(window.WebSocket){

		          socket=new WebSocket("ws://127.0.0.1:9999/chat");  //websocket用的是ws协议

		          socket.onmessage=function(event){  //收到客户端消息
					  var ta=document.getElementById("msgTxt");
					  ta.value=ta.value+"\n"+event.data;
					}
				   socket.onopen=function(event){
					 var ta=document.getElementById("msgTxt");
					 ta.value=ta.value+"\n"+"连上服务器";
				   }

				   socket.onclose=function(event){
					 var ta=document.getElementById("msgTxt");
					 ta.value=ta.value+"\n"+"退出聊天室";
				   }
		       //socket不断接受服务端传来的数据，然后通过三个事件进行处理
			}

			//客户端想发送数据
			function send(msg){
			  if(!window.WebSocket){
			     return false;
			  }
			  if(socket.readyState==WebSocket.OPEN){
			     socket.send(msg);
			  }else{
			    alert("连接没有建立");
			  }
			}
		</script>
</body>
</html>
